import 'package:flutter/material.dart';
import 'package:flutter_city_picker/city_picker.dart';
import 'package:flutter_city_picker/model/address.dart';
import 'package:flutter_hx/base/utils/toast_utils.dart';
import 'package:flutter_hx/model/address.dart';
import 'package:flutter_hx/network/HttpGo.dart';
import 'package:get/get.dart';

class AddressEditLogic extends GetxController with CityPickerListener {
  Address data = Address(
      // isDefault: "1",
      );
  bool isAdd = true;
  bool goodToSave = false;
  String? addressStr;
  // List<AddressNode>? _selectedAddress;

  @override
  void onInit() {
    if (Get.arguments != null) {
      isAdd = false;
    }
    var fromAddress = Get.arguments;

    if (fromAddress != null && fromAddress is Address) {
      ///深拷贝，防止影响上一页内容
      data = Address.fromJson(fromAddress.toJson());

      ///初始化所在地区文本
      addressStr = data.province;
      if ((data.city ?? "").isNotEmpty) {
        addressStr = "$addressStr ${data.city}";
      }
      if ((data.area ?? "").isNotEmpty) {
        addressStr = "$addressStr ${data.area}";
      }
    }
    update();
    super.onInit();
  }

  set name(String name) {
    data.realName = name;
    checkCanSave();
  }

  set phone(String phone) {
    data.phone = phone;
    checkCanSave();
  }

  set detail(String detail) {
    data.detailed = detail;
    checkCanSave();
  }

  set address(String address) {
    addressStr = address;
    checkCanSave();
  }

  saveAddress() async {
    if (!goodToSave) return;
    print("hey! dont tap!");
    if (isAdd) {
      final res = await HttpGo.instance.post("/address", data: data.toJson());
      res.ifSuccess((data) {
        ToastUtils.show("添加成功");
        Get.back();
      });
      res.ifFailure((e) {
        e.toast();
      });
    } else {
      final res = await HttpGo.instance.put("/address", data: data.toJson());
      res.ifSuccess((data) {
        ToastUtils.show("保存成功");
        Get.back();
      });
      res.ifFailure((e) {
        e.toast();
      });
    }
  }

  showCityPicker(BuildContext context) {
    CityPicker.show(
      context: context,
      cityPickerListener: this,
      // initialAddress: _selectedAddress,
      theme: ThemeData(primaryColor: const Color(0xFF00C3B3)),
    );
  }

  checkCanSave() {
    if ((data.realName ?? "").isEmpty ||
        // (data.town ?? "").isEmpty ||
        // (data.area ?? "").isEmpty ||
        // (data.city ?? "").isEmpty ||
        (data.province ?? "").isEmpty ||
        (data.phone ?? "").isEmpty ||
        (data.detailed ?? "").isEmpty) {
      goodToSave = false;
    } else {
      goodToSave = true;
    }
    update();
  }

  @override
  Future<List<AddressNode>> onDataLoad(
      int index, String code, String name) async {
    if (code.isEmpty) {
      code = "0";
    }
    List<AddressNode> list = [];
    await HttpGo.instance.get("/address/$code").then((res) {
      res.ifSuccess((data) {
        if (data != null) {
          list = data.map<AddressNode>((e) {
            e["letter"] = e["firstPinyin"];
            e["code"] = e["id"];
            return AddressNode.fromJson(e);
          }).toList();
        }
      });
    });
    return list;
  }

  @override
  void onFinish(List<AddressNode> data) {
    String str = "";
    for (int i = 0; i < data.length; i++) {
      String? name = data[i].name;
      if (i != 0) {
        str = "$str ";
      }
      str = str + (name ?? "");
      switch (i) {
        case 0:
          {
            this.data.province = name;
            break;
          }
        case 1:
          {
            this.data.city = name;
            break;
          }
        case 2:
          {
            this.data.area = name;
            break;
          }
      }
    }
    if (str.isNotEmpty) {
      address = str;
    }
  }
}
